package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.commons.utils.Constants;
import com.tanhua.model.mongo.Friend;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@DubboService
public class FriendApiImpl implements FriendApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存好友关系到环信
     * @param userId
     * @param friendId
     */
    @Override
    public void save(Long userId, Long friendId) {
        //保存自己的数据
        Query query = Query.query(Criteria.where("userId").is(userId).and("friendId").is(friendId));
        //判断好友关系是否存在
        if (!mongoTemplate.exists(query, Friend.class)){
            Friend friend = new Friend();
            friend.setUserId(userId);
            friend.setFriendId(friendId);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }
        //保存好友的数据
        Query query2 = Query.query(Criteria.where("userId").is(friendId).and("friendId").is(userId));
        //判断好友关系是否存在
        if (!mongoTemplate.exists(query2, Friend.class)){
            Friend friend2 = new Friend();
            friend2.setUserId(friendId);
            friend2.setFriendId(userId);
            friend2.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend2);
        }
    }

    /**
     * 查询好友列表
     * @param userId
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public List<Friend> fandAllcontacts(Long userId, Integer page, Integer pagesize) {
        Query query = Query.query(Criteria.where("userId").is(userId))
                .skip((page - 1) * pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        return mongoTemplate.find(query,Friend.class);
    }

    /**
     * 删除好友关系
     * @param userId
     * @param friendId
     */
    @Override
    public void delete(Long userId, Long friendId) {
        //保存自己的数据
        Query query = Query.query(Criteria.where("userId").is(userId).and("friendId").is(friendId));
        //判断好友关系是否存在,如果存在就删除
        if (mongoTemplate.exists(query, Friend.class)){
            mongoTemplate.remove(query,Friend.class);
        }

        //保存好友的数据
        Query query2 = Query.query(Criteria.where("userId").is(userId).and("friendId").is(friendId));
        //判断好友关系是否存在，存在就删除
        if (mongoTemplate.exists(query2, Friend.class)){
            mongoTemplate.remove(query2,Friend.class);
        }
    }
}
